package com.software.loginregister.util;

import android.content.Context;
import com.google.gson.Gson;
import com.software.loginregister.entity.Works;
import com.software.loginregister.entity.room.WorksCache;
import com.software.loginregister.databasesHelper.WorksCacheDao;
import com.software.loginregister.databasesHelper.AppDatabase;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HistoryManager {
    private static final int MAX_HISTORY_SIZE = 100;
    private static final long CACHE_EXPIRY_TIME = 7 * 24 * 60 * 60 * 1000; // 7 days in milliseconds
    private WorksCacheDao worksCacheDao;
    private Gson gson;

    public HistoryManager(Context context) {
        AppDatabase db = AppDatabase.getDatabase(context);
        worksCacheDao = db.worksCacheDao();
        gson = new Gson();
    }

    public void addToHistory(Works work) {
        WorksCache worksCache = new WorksCache();
        worksCache.setWorksId(work.getWorksId().intValue());
        worksCache.setCacheData(gson.toJson(work));
        worksCache.setTimestamp(System.currentTimeMillis());

        // Insert the new work
        worksCacheDao.insertAll(Collections.singletonList(worksCache));

        // Check if we need to remove old entries
        int cacheCount = worksCacheDao.getCacheCount();
        if (cacheCount > MAX_HISTORY_SIZE) {
            worksCacheDao.deleteOldestCache(cacheCount - MAX_HISTORY_SIZE);
        }

        // Delete expired cache
        long currentTime = System.currentTimeMillis();
        worksCacheDao.deleteExpiredCache(currentTime - CACHE_EXPIRY_TIME);
    }

    public List<Works> getHistory() {
        List<WorksCache> cacheList = worksCacheDao.getAllWorks();
        List<Works> worksList = new ArrayList<>();
        for (WorksCache cache : cacheList) {
            Works work = gson.fromJson(cache.getCacheData(), Works.class);
            worksList.add(work);
        }
        return worksList;
    }

    public void clearHistory() {
        worksCacheDao.deleteAll();
    }
}

